package com.gxa.saas.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.gxa.saas.pojo.Purchase;
import com.gxa.saas.pojo.Storage;
import com.gxa.saas.service.PurchaseService;
import com.gxa.saas.service.StorageService;
import com.gxa.saas.utils.JsonResult;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wxz
 */
@RestController
@RequestMapping("/purchase")
//@CrossOrigin
public class PurchaseController {

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    StorageService storageService;

    @ApiOperation("第一页分页查询")
    @RequestMapping(value = "/selectByPage",method = {RequestMethod.POST})
    public Map selectByPage(@RequestParam(value = "page") Integer offset,
                            @RequestParam(value = "size",required = false,defaultValue = "10") Integer size){
        List<Purchase> objects = purchaseService.selectByPage(size*(offset-1), size);
        JsonResult jsonResult = new JsonResult();
        Integer total = purchaseService.getTotal();
        jsonResult.setCode("200");
        jsonResult.set("total",total);
        jsonResult.setData(objects);
        return jsonResult.getMap();
    }


    @ApiOperation("审批操作")
    @RequestMapping(value = "/updateStatus",method = {RequestMethod.POST})
    public Map updateStatus(@RequestParam(value = "id",required = false) Integer id,
                            @RequestParam(value = "comments",required = false) String comments,
                            @RequestParam(value = "status",required = false) Integer status){

        JsonResult jsonResult = new JsonResult();
        Integer integer = purchaseService.updateStatus(id,comments,status);
        System.out.println(id);
        System.out.println(comments);
        System.out.println(status);
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        jsonResult.setData(integer);
        return jsonResult.getMap();
    }


    @ApiOperation("批量删除操作")
    @PostMapping("/deleteBatch")
    public Map deleteById(Integer id){
        JsonResult jsonResult = new JsonResult();
        Integer integer = purchaseService.deleteById(id);
        jsonResult.setCode("200");
        jsonResult.setData(integer);
        return jsonResult.getMap();
    }

    @ApiOperation("动态查询")
    @RequestMapping(value = "/selectByName",method = {RequestMethod.POST})
    public Map selectByName(@RequestParam (value = "from",required = false)String from,
                            @RequestParam (value = "to",required = false)String to,
                            @RequestParam (value = "supplier",required = false)String supplier,
                            @RequestParam (value = "status",required = false)String status
                            ){
        Map map1 = new HashMap();
        map1.put("from",from);
        map1.put("to",to);
        map1.put("supplier",supplier);
        map1.put("status",status);

        System.out.println(map1);

        JsonResult jsonResult = new JsonResult();
        List<Purchase> purchases = purchaseService.selectByName(map1);

        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(purchases);
        return jsonResult.getMap();
    }

    @ApiOperation("下载文件表")
    @PostMapping("/purchase")
    public void export(
        @RequestParam(value = "from",required = false) String from,
        @RequestParam(value = "to",required = false) String to,
        HttpServletResponse response) throws IOException {
        //1.获取集合
        List<Purchase> purchases = null;
        purchases = purchaseService.selectAll();
        //工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建工作表
        HSSFSheet sheet = workbook.createSheet("采购列表");
        String fileName = "采购列表.xls";
        //将文件名中的中文部分被URL编码后的内容进行解析，最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName,"UTF-8").replaceAll("\\+","%20");
        //headers表示excel表中第一行的表头 在excel表中添加表头
        String [] headers = {"编号","创建日期","供货厂商","总金额","需用日期","创建人","审批人","付款类型","状态"};
        //创建一个行对象，作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            //在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //把字段名添加到表头上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //添加数据行：表头信息占用第一行，所有要从1（第二行开始添加）
        int rowNum = 1;
        for (Purchase item : purchases) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(dateFormat.format(item.getCreateDate()));
            dataRow.createCell(2).setCellValue(item.getSupplier());
            dataRow.createCell(3).setCellValue(item.getPrice());
            dataRow.createCell(4).setCellValue(dateFormat.format((item.getNeedDate())));
            dataRow.createCell(5).setCellValue(item.getCreatePerson());
            dataRow.createCell(6).setCellValue(item.getApprover());
            dataRow.createCell(7).setCellValue(item.getPayType());
            dataRow.createCell(8).setCellValue(item.getStatus());
            rowNum++;
        }
        //返回给前端下载
        //指定文档类型
        response.setContentType("application/actet-stream");
        //指定响应头 Content-disposition附件
        response.setHeader("Content-disposition","attachment;filename="+fileName);
        //刷新流
        response.flushBuffer();
        //输出流返给前端
        workbook.write(response.getOutputStream());
    }


    @ApiOperation("第一页的根据id查询，预览详情用")
    @RequestMapping(value = "/selectById",method = {RequestMethod.POST})
    public Map selectById(Integer id){
        List<Purchase> purchases = purchaseService.selectById(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(purchases);
        return jsonResult.getMap();
    }

}
